﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using MvcShop.Core.Architecture.IoC;
using Castle.Windsor;
using MvcShop.MVC.IOC;
using Castle.Windsor.Configuration.Interpreters;
using Microsoft.Practices.ServiceLocation;
using MvcShop.MVC.IoC;
using System.Web;
using MvcShop.MVC.Controllers;
using System.Diagnostics;

namespace MvcShop.MVC
{
    [DebuggerStepThrough]
    public class MvcApplication : System.Web.HttpApplication
    {
        private static IWindsorContainer container;

        public static IWindsorContainer Container
        {
            get { return container; }
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Account",
                "Account/{action}",
                new { controller = "LoinAccount", action = "Index" }

           );

            routes.MapRoute(
                "Products",
                "Product/Get-{gategoryId}-{productId}.htm",
                new { controller = "Product", action = "Index" },
                new { gategoryId = @"\d+", productId = @"\d+" }
            );

            routes.MapRoute(
                "ProductList",
                "Product/GetList-{gategoryId}.htm",
                new { controller = "Search", action = "ListProducts" },
                new { gategoryId = @"\d+" }
            );

            routes.MapRoute(
                "ads",
                "Ads/{action}/{id}/{num}",
                new { controller = "Ads", action = "ListAd" },
                new { num = @"\d+" }
            );

            routes.MapRoute(
                "News",
                "News/Get_{newsId}/{year}/{month}/{day}.htm",
                new { controller = "News", action = "Index" }
            );
            
            routes.MapRoute(
                "Default",                                            
                "{controller}/{action}/{id}",                           
                new { controller = "Home", action = "Index", id = "" } 
                );
   
        }

        public static void RegisterIoc()
        {
            if (container == null)
            {
                //加载配置
                container = new WindsorContainer(new XmlInterpreter(System.Web.HttpContext.Current.Server.MapPath("~/Configuration/ShopIoc.config")));
            }

            AddContainer.ConfigureContainer(container);

            ServiceLocator.SetLocatorProvider(() => container.Resolve<IServiceLocator>());
            // 设置 ControllerFactory 到 WindsorControllerFactory
            System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
            RegisterIoc();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            // Log the exception.
            //ILogger logger = Container.Resolve<ILogger>();
            //logger.Error(exception);

            Response.Clear();

            HttpException httpException = exception as HttpException;
            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");

            if (httpException == null)
            {
                routeData.Values.Add("action", "Index");
            }
            else //处理错误的Http请求信息。
            {

                switch (httpException.GetHttpCode())
                {
                    case 404:
                        // 找不到页面错误。
                        routeData.Values.Add("action", "HttpError404");
                        break;
                    case 500:
                        // 服务器处理错误。
                        routeData.Values.Add("action", "HttpError500");
                        break;
                    // 这里你可以处理其他错误代码。
                    default:
                        routeData.Values.Add("action", "General");
                        break;
                }
            }

            //向处理异常页面传递要显示的错误信息。
            routeData.Values.Add("error", exception.Message);

            //清除服务器错误信息。
            Server.ClearError();
 
            //通过routeData调用的错误处理Controller
            IController errorController = new ErrorController();
            errorController.Execute(new RequestContext(
                new HttpContextWrapper(Context), routeData));

        }

        protected void Application_End()
        {
            container.Dispose();
        }
    }
}
